package com.example.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
    第一步: 自定义用户登陆的拦截器
 */

@Component
public class LoginIntercept implements HandlerInterceptor {
    /**
     * 返回true表示拦截判断通过,可以访问
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        // 1.得到HttpSession对象
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("userInfo") == null){
            return true;// 登录成功
        }
        //跳转到登录界面
        response.sendRedirect("/login.html");
        return false;
    }
}
